import pygame
from pygame.sprite import Sprite

from game_stats import GameStats
from settings import Settings


class Ship(Sprite):
    def __init__(self, ai_settings: Settings, screen: pygame.SurfaceType,
                 size=(0, 0), image_name="images/ship1.png"):
        """初始化船并设置其起始位置。"""
        super().__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        # 加载船舶图像并获得其矩形。
        try:
            self.image = pygame.image.load(image_name)
        except pygame.error as e:
            print('Cannot load image:', image_name)
            print(e)
            raise SystemExit
        if size == (0, 0):
            size = ai_settings.ship_size
        self.image = pygame.transform.scale(self.image, size)

        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # 在屏幕底部中央创建每艘新船。
        # self.rect.centerx = self.screen_rect.centerx
        # self.rect.bottom = self.screen_rect.bottom
        # 我的修改
        self.rect.left = self.screen_rect.left
        self.rect.top = self.screen_rect.bottom / 2

        # 为船的中心存储浮动值
        self.centerx = float(self.rect.left)
        self.centery = float(self.rect.top)
        print(self.centerx, self.centery)
        # Movement flags.
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def blitme(self):
        """在当前位置绘制船舶."""
        self.screen.blit(self.image, self.rect)

    def update(self, stats: GameStats):
        """根据移动标志更新船的位置。"""
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.centerx += self.ai_settings.ship_speed_factor * stats.time_passed

        if self.moving_left and self.rect.left > 0:
            self.centerx -= self.ai_settings.ship_speed_factor * stats.time_passed

        if self.moving_up and self.rect.top > 0:
            self.centery -= self.ai_settings.ship_speed_factor * stats.time_passed

        if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
            self.centery += self.ai_settings.ship_speed_factor * stats.time_passed

        # 从self更新rect对象。中心和自我中心。
        self.rect.centerx = self.centerx
        self.rect.centery = self.centery

    def center_ship(self):
        """将飞船置于左侧屏幕中央。"""
        # 我的修改
        # self.centerx = self.screen_rect.centerx
        # self.centery = self.screen_rect.bottom - self.rect.height / 2
        # 为船的中心存储浮动值
        self.rect.left = self.screen_rect.left
        self.rect.top = self.screen_rect.bottom / 2
        # 为船的中心存储浮动值
        self.centerx = float(self.rect.left) + self.rect.width / 2
        self.centery = float(self.rect.top) + self.rect.height / 2
        print(self.centerx, self.centery)
